package com.fast.develop.dm.integration.context;

import com.fast.develop.dm.core.ModuleContextFactory;
import com.fast.develop.dm.core.context.ModuleContext;
import com.fast.develop.dm.core.persistence.DomainModelManager;
import com.fast.develop.dm.core.registry.ModuleRegistry;
import com.fast.develop.dm.integration.HibernateModuleConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 莫寅
 * @createTime 2022-06-08 19:08
 * @desc：
 */
public class DefaultDomainModuleContextFactory implements ModuleContextFactory<HibernateModuleConfiguration> {

    private RequestMappingHandlerMapping requestMappingHandlerMapping;

    private Map<String, ModuleContext> domainModuleContexts = new HashMap<>();

    private static final String DEFAULT_KEY = "default";

    private ModuleContext defaultDomainModuleContext;

    private ApplicationContext applicationContext;

    private ModuleRegistry moduleRegistry;

    public DefaultDomainModuleContextFactory(ApplicationContext applicationContext, ModuleRegistry moduleRegistry, RequestMappingHandlerMapping requestMappingHandlerMapping) {
        this.requestMappingHandlerMapping = requestMappingHandlerMapping;
        this.applicationContext = applicationContext;
        this.moduleRegistry = moduleRegistry;
    }

    public DefaultDomainModuleContextFactory(RequestMappingHandlerMapping requestMappingHandlerMapping) {
        this.requestMappingHandlerMapping = requestMappingHandlerMapping;
    }

    @Override
    public ModuleContext create(HibernateModuleConfiguration moduleConfiguration) {
        return create(DEFAULT_KEY, moduleConfiguration);
    }

    @Override
    public ModuleContext create(String id, HibernateModuleConfiguration moduleConfiguration) {
        DefaultModuleContext domainModuleContext = new DefaultModuleContext(applicationContext, moduleRegistry, moduleConfiguration, requestMappingHandlerMapping);
        domainModuleContext.refresh();
        domainModuleContexts.put(id, domainModuleContext);

        if(id.equalsIgnoreCase(DEFAULT_KEY)){
            this.defaultDomainModuleContext = domainModuleContext;
        }
        return domainModuleContext;
    }

    public void destroy(){

    }


    @Override
    public ModuleContext getDomainModuleContext(String id) {
        return domainModuleContexts.get(id);
    }

    @Override
    public ModuleContext getDomainModuleContext() {
        return domainModuleContexts.get(DEFAULT_KEY);
    }

    @Override
    public DomainModelManager getDomainModelManager() {
        return defaultDomainModuleContext.getDomainModelManager();
    }
}
